package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.constant.Constants;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import com.example.demo.util.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Result login(String userName, String password, HttpServletRequest request){
        log.info("userName:"+userName+",password:"+password);
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            //账号密码为空
            return Result.fail(-2,"账号或者密码为空");
        }
        //验证密码是否正确
        User user = userService.selectUserByName(userName);
        if (user==null || !password.equals(user.getPassword())){
            return Result.fail(-3,"密码错误");
        }
//        if (user==null || !SecurityUtil.decrypt(password,user.getPassword())){
//            return Result.fail(-3,"密码错误");
//        }

        //存入Session
        HttpSession session = request.getSession(true);
        user.setPassword("");
        session.setAttribute(Constants.SESSION_USER_INFO,user);
        return Result.success(200,true);
    }
    /**
     * 获取当前用户登录信息
     */
    @RequestMapping("/getUserInfo")
    public User getUserInfo(HttpServletRequest request) {
        return (User) request.getSession().getAttribute(Constants.SESSION_USER_INFO);
    }
    /**
     * 获取博客作者信息
     */
    @RequestMapping("/getAuthorInfo")
    public User getAuthorInfo(Integer blogId){
        if(blogId==null || blogId<0){
            return null;
        }
        return userService.getAuthorInfoByBlogId(blogId);
    }

    @RequestMapping("/logout")
    public boolean logout(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if(session!=null){
            session.removeAttribute(Constants.SESSION_USER_INFO);
            return true;
        }
        log.error("用户退出失败，userid:");
        return false;
    }
}
